package xsource

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 创建批次产品
//
//	id	批次ID
//	num	创建条数
func CreateChild(id, num uint) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	for i := uint(0); i < num; i++ {
		for {
			child := SourceChild{
				SourceId:  id,
				GoodsCode: xstring.UUID(),
				CreatedAt: time.Now().Format(time.DateTime),
			}
			if err := _default.DB.Save(&child).Error; err != nil {
				xlog.Error("溯源批次产品插入失败", err)
				continue
			}
			break
		}
	}
	return nil
}

// 创建批次产品【根据已有商品code】
//
//	id	批次ID
//	child	待存入的goods_code
func CreateChildCode(id uint, child []string) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	for i := 0; i < len(child); i++ {
		child := SourceChild{
			SourceId:  id,
			GoodsCode: child[i],
			CreatedAt: time.Now().Format(time.DateTime),
		}
		if err := _default.DB.Save(&child).Error; err != nil {
			return xlog.EE("溯源批次产品插入失败", err)
		}
	}
	return nil
}
